package com.zhangxin.aiInterview.manager.wsserver;

import com.zhangxin.aiInterview.model.entity.User;
import com.zhangxin.aiInterview.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * ws连接请求拦截器
 */
@Slf4j
@Component
public class WsHandshakeInterceptor implements HandshakeInterceptor {
    @Resource
    private UserService userService;

    /**
     * 握手拦截器
     * @param request http请求
     * @param response http响应
     * @param wsHandler ws处理器
     * @param attributes wsSession中存储空间
     * @return
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes){
        log.info("握手拦截器。。。。");
        //转换为HttpServletRequest请求
        if(request instanceof ServletServerHttpRequest){
            HttpServletRequest httpServletRequest = ((ServletServerHttpRequest) request).getServletRequest();
            //获取用户登录信息
            User loginUser = userService.getLoginUser(httpServletRequest);
            //获取用户面试类型
            Integer interviewType = userService.getInterviewType(httpServletRequest);
            //将用户id存入到当前ws连接session中
            Long userId = loginUser.getId();
            attributes.put("userId",userId);
            attributes.put("interviewType",interviewType);
            return true;
        }
        return false;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
